var bmap = require("../../libs/bmap-wx.min.js");
Page({
  data: {
    showHalfdialogSearch: false,
    showDialogCarInfo: false,
    showPopupCarList: false,
    buttonsDialogCarInfo: [{ text: '取消' }, { text: '轨迹回放' }],

    carTitle: '',
    carRange: '',
    carStatus: ['全部', '在线', '离线'],
    carStatusValue: '全部',
    carStatusCode: '全部',
    carType: ['全部', '机扫车', '小型机扫车', '吸尘车', '洒水车', '高压清洗车', '洗路车', '除雪车'],
    carTypeValue: '全部',

    carDetailInfo: {},

    originalMarkers: [],
    markers: [],
    circle: [],
    includePoints: [],
    latitude: "40.049191",
    longitude: "116.280190",
    listPopup: [],
  },
  onLoad: function () {
    var that = this;
    var BMap = new bmap.BMapWX({
      ak: "tEmJ2Qdq06YVa1mZDxrz509Cquqom80H",
    });
    wx.getLocation({
      type: 'wgs84',
      success (res) {
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        });
      }
    })
    this.getCurrentCarInfo();
  },
  onPopupCell (e) {
    // console.log(e.detail)
    var marker = this.data.listPopup[e.detail]
    // console.log(marker)
    this.setData({
      showDialogCarInfo: true,
      showPopupCarList: false,
      carDetailInfo: marker
    })
  },
  openHalfdialogSearch () {
    this.setData({
      showHalfdialogSearch: true
    })
  },
  tapDialogButton (e) {
    if (e.detail.index === 1) {
      wx.navigateTo({
        url: '../mapHistoryTrajectory/mapHistoryTrajectory?VID=' + this.data.carDetailInfo.VID
      })
    }
    this.setData({
      showDialogCarInfo: false
    })
  },
  onMarkerTap (e) {
    if (this.data.showHalfdialogSearch || this.data.showPopupCarList || this.data.showDialogCarInfo) {
      return;
    }
    var marker = this.data.markers.find(marker => marker.id === e.detail.markerId);
    marker.lastGPSTime = marker.lastGPSTime.replace('T', ' ')
    console.log(marker)
    this.setData({
      showDialogCarInfo: true,
      carDetailInfo: marker
    })
  },
  bindCarTitle (e) {
    this.setData({
      carTitle: e.detail.value
    });
  },
  // 输入距离事件
  bindCarRange (e) {
    var that = this;
    that.setData({
      carRange: e.detail.value,
    });
    this.drawCircle();
  },
  // 绘制圆形
  drawCircle () {
    var that = this;
    const {
      latitude,
      longitude,
      carRange
    } = this.data;
    var radius = Number(carRange);
    if (radius <= 0) {
      wx.showToast({
        title: '半径需大于0',
        icon: 'none'
      });
      return;
    }
    // 计算边缘点以调整视野
    const deltaLat = radius / 111319;
    const deltaLon = radius / (111319 * Math.cos((latitude * Math.PI) / 180));
    const includePoints = [{
      latitude: latitude + deltaLat,
      longitude
    },
    {
      latitude: latitude - deltaLat,
      longitude
    },
    {
      latitude,
      longitude: longitude + deltaLon
    },
    {
      latitude,
      longitude: longitude - deltaLon
    },
    ];

    // 圆形配置
    const circle = {
      latitude: this.data.latitude,
      longitude: this.data.longitude,
      color: "#FF000010",
      fillColor: "#FF000020",
      radius: radius
    };

    that.setData({
      circles: [circle],
      includePoints,
    });

    this.filterVehicles(this.data.carRange);
  },
  // 筛选车辆
  filterVehicles (maxDistance) {
    const {
      latitude,
      longitude,
      originalMarkers
    } = this.data;
    const list = originalMarkers.filter(vehicle => {
      const distance = this.calculateDistance(
        latitude,
        longitude,
        vehicle.latitude,
        vehicle.longitude
      );
      return distance <= maxDistance;
    });

    // 更新筛选后的车辆数据
    this.setData({
      listPopup: list,
      showPopupCarList: true,
    });
  },
  // 计算两点之间的距离（单位：米）
  calculateDistance (lat1, lng1, lat2, lng2) {
    const toRadians = (angle) => (angle * Math.PI) / 180;
    const R = 6371000; // 地球半径，单位：米
    const dLat = toRadians(lat2 - lat1);
    const dLng = toRadians(lng2 - lng1);
    const a =
      Math.sin(dLat / 2) * Math.sin(dLat / 2) +
      Math.cos(toRadians(lat1)) *
      Math.cos(toRadians(lat2)) *
      Math.sin(dLng / 2) *
      Math.sin(dLng / 2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    return R * c;
  },
  // 车辆筛选——类型
  bindCarTypeChange (e) {
    this.setData({
      carTypeValue: this.data.carType[parseInt(e.detail.value)]
    });
  },
  // 车辆筛选——在线状态
  bindCarStatusChange (e) {
    this.setData({
      carStatusValue: this.data.carStatus[parseInt(e.detail.value)]
    });
    var str = '';
    switch (parseInt(e.detail.value)) {
      case 1:
        str = '0'
        break;
      case 2:
        str = '6'
        break;
      default:
        str = '全部'
        break;
    }
    this.setData({
      carStatusCode: str
    });
  },
  searchByMap () {
    var list = this.getSearch();
    this.setData({
      markers: list,
      showHalfdialogSearch: false,
    });
  },
  searchByTable () {
    var list = this.getSearch();
    console.log(list.length)
    this.setData({
      listPopup: list,
      showPopupCarList: true,
      showHalfdialogSearch: false,
    });
  },
  getSearch () {
    var list = [];
    // console.log(this.data.originalMarkers.length)
    this.data.originalMarkers.forEach(element => {
      // console.log(this.data.carTitle)
      if (this.data.carTitle !== '') {
        if (element.title.indexOf(this.data.carTitle) < 0) {
          // console.log(element.title)
          return;
        }else {
          console.log(element.title)
        }
      }
      // if (!element.CLIENTNO.includes(groupingValue)) {
      //   return;
      // }
      if (this.data.carTypeValue !== '全部' && element.type != this.data.carTypeValue) {
        return;
      }
      if (this.data.carStatusCode !== '全部' && element.status != this.data.carStatusCode) {
        return;
      }
      list.push(element);
    });
    return list;
  },
  // 关闭车辆信息弹窗
  onPopupClose () {
    this.setData({
      showPopupCarList: false,
    });
  },
  // 获取信息
  getCurrentCarInfo () {
    var CLIENT_NO = wx.getStorageSync("CLIENT_NO");

    var that = this;
    wx.request({
      url:
        "https://www.ejingyou.cn/ServerHuanwei/CompanyapiBDEapi/Vehicle/GetCarListCurrentVehicleCityXCX",
      data: {
        CLIENTNO: CLIENT_NO,
        CARSTATUS: "1",
        CARTYPE: "",
        CARGROUP: "",
        LICENSEPLATE: "",
        isCX: "0",
      },
      header: {
        "content-type": "application/json", // 默认值
      },
      success: (res) => {
        var list = [];
        var i = 0;
        res.data.forEach((element) => {
          i++;
          var dataC = {
            id: i,
            VID: element.VID,
            title: element.LICENSEPLATE,
            type: element.CARTYPE,
            status: element.STATUS,
            clientName: element.CLIENTNAME,
            lastGPSTime: element.GPSTIME,
            longitude: element.LNG,
            latitude: element.LAT,
            height: 50,
            width: 50,
          };
          var strImage = "";
          switch (element.CARTYPE) {
            case "除雪车":
              strImage = "1";
              break;
            case "高压清洗车":
              strImage = "2";
              break;
            case "机扫车":
              strImage = "3";
              break;
            case "洒水车":
              strImage = "4";
              break;
            case "吸尘车":
              strImage = "5";
              break;
            case "洗路车":
              strImage = "6";
              break;
            case "小型机扫车":
              strImage = "7";
              break;
            default:
              strImage = "8";
              break;
          }
          dataC.iconPath =
            "../../image/markerVehicle/" + strImage + element.STATUS + "B.png";
          list.push(dataC);
        });
        that.setData({
          markers: list,
          originalMarkers: list,
          latitude: list[0].latitude,
          longitude: list[0].longitude,
        });
      },
    });
  },
});
